import { defineStore } from "pinia"
import { 
  getLoginCaptcha,
  login,
  logout,
  register
} from "@/api/login/index"
import type { 
} from "@/api/login/types"
import Storage from '@/assets/js/storage'
import Token from '@/assets/js/token'

export const loginStore = defineStore('login', {
  state: () => ({
    token: '',
    refresh_token: ''
  }),
  actions: {
    setLoginInfo(data: any) {
      Storage.set('userId', data.userId)
      Token.setToken(data.token, 'auth')
    },
    async getLoginCaptcha(params: any) {
      try {
        const data = await getLoginCaptcha(params)
        return Promise.resolve(data)
      } catch(error) {
        return Promise.reject(error)
      }
    },
    async login(params: any) {
      try {
        const data = await login(params)
        if (data.state === 'OK' && data.body) {
          this.setLoginInfo(data?.body)
        }
        return Promise.resolve(data)
      } catch(error) {
        return Promise.reject(error)
      }
    },
    async logout(params: any) {
      try {
        const data = await logout(params)
        return Promise.resolve(data)
      } catch(error) {
        return Promise.reject(error)
      }
    },
    async register(params: any) {
      try {
        const data = await register(params)
        return Promise.resolve(data)
      } catch(error) {
        return Promise.reject(error)
      }
    }
  },
  getters: {
  }
})
